package com.hsnn.medstgmini.crypto.impl;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.lang.StringUtils;

import com.hsnn.medstgmini.crypto.CryptoManager;

/**
 * @category 加密解密
 * @author 单大伟
 * @date 2015-08-30
 */
public class CryptoManagerImpl implements CryptoManager {
	
	/**
	 * @category 加密
	 * @author 单大伟
	 * @date 2015-08-30
	 * @sKey 加密秘钥
	 * @message 要加密的内容
	 * @return 加密结果
	 */
    public static byte[] encrypt(SecretKey sKey, String message) throws Exception {  	
    	final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
    	final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
    	cipher.init(Cipher.ENCRYPT_MODE, sKey, iv);

    	final byte[] plainTextBytes = message.getBytes("utf-8");
    	final byte[] cipherText = cipher.doFinal(plainTextBytes);
    	return cipherText;
    }

    public static byte[] encrypt(String key, String message) throws Exception {

    	if (key.length() >= 24) {
    		key = key.substring(0, 24);
    	} else {
    		key = StringUtils.leftPad("0", 24);
    	}
    	
    	SecretKey secretKey = new SecretKeySpec(key.getBytes(), "DESede");
        return encrypt(secretKey, message);
    }
    
	/**
	 * @category 解密
	 * @author 单大伟
	 * @date 2015-08-30
	 * @sKey 解密秘钥
	 * @message 要解密的内容
	 * @return 解密结果
	 */
    public static String decrypt(SecretKey sKey, byte[] message) throws Exception {
    	final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
    	final Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
    	decipher.init(Cipher.DECRYPT_MODE, sKey, iv);

    	final byte[] plainText = decipher.doFinal(message);
    	return new String(plainText, "UTF-8");
    }
    
    public static String decrypt(String key, byte[] message) throws Exception {
    	
    	if (key.length() >= 24) {
    		key = key.substring(0, 24);
    	} else {
    		key = StringUtils.leftPad("0", 24);
    	}
    	
    	SecretKey secretKey = new SecretKeySpec(key.getBytes(), "DESede");
        return decrypt(secretKey, message);
    }
}